#!/bin/bash
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# This file is a part of the CANN Open Software.
# Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
# Please refer to the License for details. You may not use this file except in compliance with the License.
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
# See LICENSE in the root of the software repository for the full text of the License.
# ======================================================================================================================

export IS_PERF="0"

SHORT=r:,v:,p:,
LONG=run-mode:,soc-version:,perf:,
OPTS=$(getopt -a --options $SHORT --longoptions $LONG -- "$@")
eval set -- "$OPTS"
while :
do
    case "$1" in
        (-r | --run-mode )
            RUN_MODE="$2"
            shift 2;;
        (-v | --soc-version )
            SOC_VERSION="$2"
            shift 2;;
        (-p | --perf)
            IS_PERF="$2"
            shift 2;;
        (--)
            shift;
            break;;
        (*)
            echo "[ERROR] Unexpected option: $1";
            break;;
    esac
done

# Check invalid input
if [[ ! "${SOC_VERSION}" =~ ^Ascend910 ]]; then
    echo "[ERROR] Unsupported SocVersion: ${SOC_VERSION}"
    exit 1
fi

if [ "${RUN_MODE}" != "npu" ] && [ "${RUN_MODE}" != "sim" ] && [ "${RUN_MODE}" != "cpu" ]; then
    echo "[ERROR] Unsupported RUN_MODE: ${RUN_MODE}, which can only be cpu/sim/npu."
    exit 1
fi

if [ "${IS_PERF}" != "0" ] && [ "${IS_PERF}" != "1" ]; then
    echo "[ERROR] Unsupported IS_PERF: ${IS_PERF}, which can only be 0 or 1."
    exit 1
fi

# only npu mode support is_perf = 1
if [ "${IS_PERF}" == "1" ] && [ "${RUN_MODE}" != "npu" ]; then
    echo "[ERROR] Unsupported IS_PERF: ${IS_PERF} while RUN_MODE is ${RUN_MODE}."
    exit 1
fi

rm -rf build
mkdir build
cd build

source $ASCEND_HOME_DIR/bin/setenv.bash
export LD_LIBRARY_PATH=${ASCEND_HOME_DIR}/tools/simulator/${SOC_VERSION}/lib:$LD_LIBRARY_PATH
export ASCEND_TOOLKIT_HOME=${ASCEND_HOME_DIR}
set -euo pipefail

cmake  -DRUN_MODE=${RUN_MODE} -DSOC_VERSION=${SOC_VERSION} -DASCEND_CANN_PACKAGE_PATH=${ASCEND_HOME_DIR} ..
make -j16

cd ../

rm -rf input
mkdir input
rm -rf output
mkdir output

rm -rf bin/
mkdir -p bin
cd bin
cp ../build/ascendc_matmul_a2_b2_share_bbit ./

python3 -u ../scripts/exec_test.py -r ${RUN_MODE} -p ${IS_PERF}
